package com.ruoyi.media.tiktokCover.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dtflys.forest.http.ForestQueryMap;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.media.forestApi.DouyinApi;
import com.ruoyi.media.tiktokCover.domain.MediaTiktokCover;
import com.ruoyi.media.tiktokCover.domain.vo.TiktokVo;
import com.ruoyi.media.utils.XStringUtils;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.media.tiktokCover.domain.vo.MediaTiktokCoverVo;
import com.ruoyi.media.tiktokCover.domain.bo.MediaTiktokCoverBo;
import com.ruoyi.media.tiktokCover.service.IMediaTiktokCoverService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 抖音封面列
 *
 * @author dqw
 * @date 2023-03-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/media/tiktokCover")
public class MediaTiktokCoverController extends BaseController {

    private final IMediaTiktokCoverService iMediaTiktokCoverService;

    private final DouyinApi douyinApi;

    /**
     * 查询抖音封面列列表
     */
    @SaCheckPermission("media:tiktokCover:list")
    @GetMapping("/list")
    public TableDataInfo<MediaTiktokCoverVo> list(MediaTiktokCoverBo bo, PageQuery pageQuery) {
        return iMediaTiktokCoverService.queryPageList(bo, pageQuery);
    }


    /**
     * 获取第一条数据
     */
    @SaCheckPermission("media:tiktokCover:list")
    @GetMapping("/listOne")
    public R<MediaTiktokCover> listOne() {
        LambdaQueryWrapper<MediaTiktokCover> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MediaTiktokCover::getIsUse,0);
        queryWrapper.isNotNull(MediaTiktokCover::getUniqueId);
        queryWrapper.last("limit 1");
        return R.ok(iMediaTiktokCoverService.getOne(queryWrapper));
    }


    /**
     * 已使用的数据修改为已使用
     */
    @SaCheckPermission("media:tiktokCover:list")
    @GetMapping("/updateAccount/{id}")
    public R<Boolean> updateAccount(@PathVariable Long id) {
        MediaTiktokCover mediaTiktokCover = new MediaTiktokCover();
        mediaTiktokCover.setIsUse(1);
        mediaTiktokCover.setId(id);
        boolean res = iMediaTiktokCoverService.updateById(mediaTiktokCover);
        return R.ok(res);
    }



    /**
     * 解析页面数据
     */
    @SaCheckPermission("media:tiktokCover:add")
    @GetMapping("/createCover")
    public R<String> createCover() {
        String indexCookies = "cookie: douyin.com; ttwid=1%7CrJShWKCgJJHOrRNhqNCjhktAvZKkCPyZCh31Lt0_xrQ%7C1681523423%7C2b987ba3d070ba0f0bf8ccabda183fdb51392c653e5f71beefefd7d1ed9ded49; douyin.com; strategyABtestKey=%221681523425.058%22; VIDEO_FILTER_MEMO_SELECT=%7B%22expireTime%22%3A1682128225074%2C%22type%22%3A1%7D; passport_csrf_token=fb54c77868a648eb53c20cfdc1aee9a2; passport_csrf_token_default=fb54c77868a648eb53c20cfdc1aee9a2; s_v_web_id=verify_lghbmqqw_3z5F41ML_trII_44MC_9afH_Rodus4A101Yi; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtY2xpZW50LWNzciI6Ii0tLS0tQkVHSU4gQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbk1JSUJEakNCdFFJQkFEQW5NUXN3Q1FZRFZRUUdFd0pEVGpFWU1CWUdBMVVFQXd3UFltUmZkR2xqYTJWMFgyZDFcclxuWVhKa01Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRUdvaEMreXVQNVp1SndQWlRoREtpT1F5eFxyXG5xZTFwc3lHYkRmb1BvMUtSWlorVnAwRFZuZE42RlR2aElaODMwNFk4RnM2elJsMkZxOHhYZzBYUEROMjdEcUFzXHJcbk1Db0dDU3FHU0liM0RRRUpEakVkTUJzd0dRWURWUjBSQkJJd0VJSU9kM2QzTG1SdmRYbHBiaTVqYjIwd0NnWUlcclxuS29aSXpqMEVBd0lEU0FBd1JRSWdmVGtVQTNSbFAxTTdFVkgrSlRITlo4Zm9CVFd1UGNmWEUwcFFLbmhZQ2xVQ1xyXG5JUUNia0N3bXFaODBtcUZCemgxWmUxdDNnSU1Hd3JldVFxT2ZUTGJMVHR2Q1RBPT1cclxuLS0tLS1FTkQgQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbiJ9; csrf_session_id=98029203619c5aa23172c323ae767c46; ttcid=93d405bf90674428a44db5c37a79b54537; download_guide=%221%2F20230415%22; msToken=1ZF1XIdzR0KfJCSLnTeLf2CIgMm9LMjlcnWLQuvt-aPvz9beUaJBm8ZhXJhZqtwxwOm2qWnZtSKUSQIPCC5VGTt3Kn-za8jQeUT4v59SLFC0n4fSUS2Y9SP9iilRLw==; __ac_nonce=0643a04f100a7a88cb473; __ac_signature=_02B4Z6wo00f012EnwfgAAIDD4SU7uWJYfRNhB8VAALx.RatcYEm82UFVNvnv7MgHuhKzzZnKbYYF26YDlPxzSc1uxyL4UqUEFs8f7R5QxzJQ84rtZpyoBobpr.sxTJsctdigQl7Olk37LtXXc9; home_can_add_dy_2_desktop=%221%22; msToken=g0dV4QHWC2bHSMpbRgxk0ziydLpYsDAidCSDBxg1yKClmp8TQZfwDk-SZ8E3vB6gaVmxtH4lqThtO3uI-jULbZhPtSz_RzPnhHSBby1xtYWLTQrlEx0SDHv3R7uInA==; tt_scid=IcOrMabZOdXOs4WEXND5DYUu2N4PsrdBgfQKuCDfRsrull6XE3OJ1KeHGqU2KZ5ie1eb";
        LambdaQueryWrapper<MediaTiktokCover> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(MediaTiktokCover::getUniqueId);
        List<MediaTiktokCover> mediaTiktokCovers =  iMediaTiktokCoverService.list(queryWrapper); //获取列表
        for(MediaTiktokCover item : mediaTiktokCovers){

           MediaTiktokCover mediaTiktokCover = new MediaTiktokCover();
           mediaTiktokCover.setId(item.getId());

           String indexUrl = item.getUserIndex(); //获取用户首页
           String secUserId = "";
            String result = ""; // html body
            if(XStringUtils.isEmpty(indexUrl)){
                continue;
            }
            if(indexUrl.contains("v.douyin.com")){  //解析短链接参数
                try{
                    ForestResponse response =  douyinApi.jiexidouyin(indexUrl,indexCookies);
                    if (response.isRedirection()) {
                        // 获得即将跳转的请求对象
                        ForestRequest redirectReq = response.redirectionRequest();
                        // 执行跳转
                        secUserId = redirectReq.getUrl().substring(redirectReq.getUrl().lastIndexOf("/") + 1);
                         result = redirectReq.executeAsString();

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{  //长链接无需解析
                if(indexUrl.contains("?")){
                    secUserId =  indexUrl.substring(indexUrl.lastIndexOf("/") + 1,indexUrl.indexOf("?"));
                }else{
                    secUserId = indexUrl.substring(indexUrl.lastIndexOf("/") + 1);
                }
                result =  douyinApi.jiexidouyin(indexUrl,indexCookies).getContent();
            }
            if(StringUtils.isEmpty(secUserId)){
                throw new RuntimeException("cookies参数失效");
            }

            if(XStringUtils.isNotEmpty(result)){
                Element body = Jsoup.parse(result).body().children().get(0);
                Elements userInfo = body.getElementsByClass("p6_XFKN2"); //获取账号数据
                if(userInfo.size() < 1){
                    continue;
                }
                String age = userInfo.get(0).getElementsByClass("N4QS6RJT").text();//年龄
                Elements elements1 = body.getElementsByClass("HKFI7GBq"); //获取作品数据
                List<Map<String,Object>> mapList = new ArrayList<>();

                mediaTiktokCover.setAge(age);

                for (Element videoCover : elements1) {
                    Map<String,Object> coverLinks = new HashMap<>();
                    String coverImg = "https:" +  videoCover.select("img").attr("src").replaceAll("amp;","");
                    String likeNum = videoCover.getElementsByClass("jjKJTf4P").get(0).text();

                    int isTop = 0;
                    if(videoCover.toString().contains("置顶")){
                        isTop = 1;
                    }
                    String readNum = "";
                    if(likeNum.contains("万")){
                        likeNum = likeNum.replace("万","");
                        if(likeNum.contains(".")){
                            likeNum = likeNum.replace(".","");
                            likeNum += "000";
                        }else{
                            likeNum += "0000";
                        }
                    }
                    BigDecimal bigDecimal = new BigDecimal(likeNum);
                    readNum =  bigDecimal.multiply(new BigDecimal(50)).toString();
                    coverLinks.put("coverImg",coverImg);
                    coverLinks.put("isTop",isTop);
                    String readStr = XStringUtils.resetWan(Integer.parseInt(readNum));
                    coverLinks.put("readNum",readStr);
                    mapList.add(coverLinks);
                }
                mediaTiktokCover.setUserIndex("https://www.douyin.com/user/" + secUserId);
                String jsonCoverLinks = JSONObject.toJSON(mapList).toString();
                mediaTiktokCover.setCoverLinks(jsonCoverLinks);
            }else{
                throw new RuntimeException("cookies参数失效！");
            }

            //请求抖音数据
            Map<String,Object> param = new HashMap<>();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("sec_user_id",secUserId);
            param.put("group","zzz");
            param.put("name","hlg");
            param.put("action","hello3");
            param.put("param",jsonObject);
            String res =  douyinApi.getDouyinUserInfo(param);
            if(res.contains("sec_uid")){

                JSONObject userInfo =  JSONObject.parseObject(res).getJSONObject("data").getJSONObject("user");
                TiktokVo tiktokVo = JSONObject.toJavaObject(userInfo, TiktokVo.class);
                //手机封面背景
                String  coverUrl = tiktokVo.getWhite_cover_url().getJSONObject(0).getJSONArray("url_list").getString(0);
                //头像链接
                String  avatar = tiktokVo.getAvatar_300x300().getJSONArray("url_list").getString(0);
                //个人介绍
                String signature = tiktokVo.getSignature();
                signature = signature.replaceAll("\n","/n");

                System.out.println(signature);
                //关注数
                int followingCount = tiktokVo.getFollowing_count();

                //领域介绍
                String  customVerify = tiktokVo.getCustom_verify();
                //位置信息
                String ipLocal = XStringUtils.getNullBlankStr(tiktokVo.getIp_location());
                if(ipLocal.contains("：")){
                    ipLocal = ipLocal.substring(ipLocal.indexOf("：") + 1);
                }


                //卡片信息
                if(tiktokVo.getCard_entries() != null){
                    mediaTiktokCover.setCardEntries(tiktokVo.getCard_entries().toString());
                }

                //当前粉丝数
                String fansSb = XStringUtils.resetWan(tiktokVo.getMplatform_followers_count());
                mediaTiktokCover.setFansNum(fansSb);

                //总获赞
                String totalFav = XStringUtils.resetWan(tiktokVo.getTotal_favorited());
                mediaTiktokCover.setTotalFavorited(totalFav);

                Random random = new Random();
                int max = 500;
                int min = 1;
                int s = random.nextInt(max) % (max-min+1) + min;

                mediaTiktokCover.setVisitor(String.valueOf(random.nextInt(max) % (max-min+1) + min));
                mediaTiktokCover.setFriend(String.valueOf(s));


                //抖音号
                String uniqueId =  tiktokVo.getUnique_id();
                mediaTiktokCover.setNickname(tiktokVo.getNickname());
                mediaTiktokCover.setCoverUrl(coverUrl);
                mediaTiktokCover.setSignature(signature);
                mediaTiktokCover.setFollowingCount(String.valueOf(followingCount));

                mediaTiktokCover.setAvatar(avatar);
               // mediaTiktokCover.setCustomVerify(customVerify);

                mediaTiktokCover.setIpCity(ipLocal);
                mediaTiktokCover.setUniqueId(XStringUtils.isEmpty(uniqueId) ? tiktokVo.getShort_id() : uniqueId);
                iMediaTiktokCoverService.updateById(mediaTiktokCover);
            }
            System.out.println(res);
        }

        return R.ok("");
    }






    /**
     * 导出抖音封面列列表
     */
    @SaCheckPermission("media:tiktokCover:export")
    @Log(title = "抖音封面列", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(MediaTiktokCoverBo bo, HttpServletResponse response) {
        List<MediaTiktokCoverVo> list = iMediaTiktokCoverService.queryList(bo);
        ExcelUtil.exportExcel(list, "抖音封面列", MediaTiktokCoverVo.class, response);
    }

    /**
     * 获取抖音封面列详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("media:tiktokCover:query")
    @GetMapping("/{id}")
    public R<MediaTiktokCoverVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iMediaTiktokCoverService.queryById(id));
    }

    /**
     * 新增抖音封面列
     */
    @SaCheckPermission("media:tiktokCover:add")
    @Log(title = "抖音封面列", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody MediaTiktokCoverBo bo) {
        return toAjax(iMediaTiktokCoverService.insertByBo(bo));
    }

    /**
     * 修改抖音封面列
     */
    @SaCheckPermission("media:tiktokCover:edit")
    @Log(title = "抖音封面列", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody MediaTiktokCoverBo bo) {
        return toAjax(iMediaTiktokCoverService.updateByBo(bo));
    }

    /**
     * 删除抖音封面列
     *
     * @param ids 主键串
     */
    @SaCheckPermission("media:tiktokCover:remove")
    @Log(title = "抖音封面列", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iMediaTiktokCoverService.deleteWithValidByIds(Arrays.asList(ids), true));
    }



    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "抖音封面", MediaTiktokCoverVo.class, response);
    }


    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "抖音封面列", businessType = BusinessType.IMPORT)
    @SaCheckPermission("media:tiktokCover:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<MediaTiktokCoverVo> result = ExcelUtil.importExcel(file.getInputStream(), MediaTiktokCoverVo.class, true);
        List<MediaTiktokCoverVo> mediaTiktokCoverVos =  result.getList();
        for(MediaTiktokCoverVo item : mediaTiktokCoverVos){
            MediaTiktokCover mediaTiktokCover = BeanCopyUtils.copy(item, MediaTiktokCover.class);
            iMediaTiktokCoverService.save(mediaTiktokCover);
        }
        return R.ok(result.getAnalysis());
    }
}
